package com.sxt.service.impl;

import com.sxt.entity.Area;
import com.sxt.mapper.AreaMapper;
import com.sxt.service.AreaService;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liangtiandong
 * @since 2019-12-17
 */
@Service(timeout = 10000) // 这里面给他设置一个值后,服务的消费者怎么知道超时时间需要10s/ 在注册时,在服务节点里面,有个timeout的属性
@Slf4j
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements AreaService {

	@Autowired
	private AreaMapper  areaMapper;
	
	@Override
	public List<Area> listByPid(Long pid) {
		Assert.notNull(pid,"父id不能为空");
		log.info("查询pid为{}的儿子",pid);
		return areaMapper.selectList(new LambdaQueryWrapper<Area>().eq(Area::getParentId, pid));
	}

	/**
	 * 新增一个区域
	 */
	@Override
	public boolean save(Area entity) {
		Assert.notNull(entity, "新增的数据不能为空");
		log.info("新增的数据为{}",JSONUtil.toJsonStr(entity));
		if(!StringUtils.hasText(entity.getAreaName())) {
			throw new IllegalArgumentException("区域的名称不能为空");
		}
		if(entity.getParentId()==null || entity.getParentId()==0) {
			entity.setParentId(0L);
			entity.setLevel(1);
		}else {
			Area parent = getById(entity.getParentId());
			entity.setLevel(parent.getLevel() +1);
		}
		return super.save(entity);
	}
	
	@Override
	public boolean updateById(Area entity) {
		Assert.notNull(entity, "要修改的数据不能为null");
		Area dbArea = getById(entity.getAreaId());
		if(dbArea==null) {
			throw new RuntimeException("要修改的数据不存在");
		}
		if(dbArea.getAreaName().equals(entity.getAreaName())) {
			 // 名称.,不需要修改
			return true ;
		}
		dbArea.setAreaName(entity.getAreaName());
		return super.updateById(dbArea);
	}
}
